package cn.ky.jzk.controller;

import cn.ky.jzk.model.User;
import cn.ky.jzk.service.UploadService;
import cn.ky.jzk.service.UserService;
import cn.ky.jzk.swagger.api.UploadControllerApi;
import cn.ky.jzk.util.*;
import cn.ky.jzk.vo.Response;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.apache.commons.io.FilenameUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author kevin
 */
@RestController
@RequestMapping("/upload")
public class UploadController extends BaseController implements UploadControllerApi, AliOssImgBedConstants {
    @Autowired
    @Qualifier(value = "uploadServiceImpl")
    private UploadService uploadService;

    @Autowired
    @Qualifier("userServiceImpl")
    private UserService userService;

    public final static String MESSAGE_COMMIT = "commit";

    public final static String MESSAGE_STATUS = "status";

    @Override
    @GetMapping("/exportExcel")
    @ResponseBody
    public void exportExcel(HttpServletRequest request, HttpServletResponse response) {
        List<User> users = userService.select();
        String[] title = {"用户名", "密码", "昵称", "性别", "联系电话", "电子邮箱",
                "密保问题", "密保答案", "头像链接"};
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook("用户导出表", title, users, null);

        //将文件存到指定位置
        try {
            this.setResponseHeader(response, "用户导出表");
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @PostMapping("/importExcel")
    @ResponseBody
    @Override
    public Response<String> importExcel(@RequestParam("excelFile") MultipartFile multipartFile) {
        String info = uploadService.importExcel(multipartFile);
        return dataAnalyse(info.equals("导入成功") ? info : null, 408, info);
    }

    @Override
    @PostMapping("/saveImg")
    @ResponseBody
    public Response<Map<String, Object>> saveImg(@RequestParam(value = "fileImg", required = true) MultipartFile fileImg) throws Exception {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            String fileName = StringUtils.format("{}/{}.{}", DateUtils.datePath(),
                    FilenameUtils.getBaseName(fileImg.getOriginalFilename()), getExtension(fileImg));
            OSS ossClient = new OSSClientBuilder().build(END_POINT, ACCESSKEY_ID, ACCESSKEY_SECRET);
            ossClient.putObject(BUCKET_NAME, fileName, fileImg.getInputStream());
            ossClient.shutdown();
            resultMap.put("resultImgUrl", "https://" + BUCKET_NAME + "." + END_POINT + "/" + fileName);
            return getSuccessResult(resultMap);
        } catch (Exception e) {
            return getFailResult(404, "上传失败");
        }

    }


    //发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 获取文件名的后缀
     *
     * @param file 表单文件
     * @return 后缀名
     */
    public static final String getExtension(MultipartFile file)
    {
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        if (StringUtils.isEmpty(extension))
        {
            extension = MimeTypeUtils.getExtension(Objects.requireNonNull(file.getContentType()));
        }
        return extension;
    }
}
